import {
  createRouter,
  createWebHashHistory
} from "vue-router";
import NotFound from '@/views/error-page/404.vue'
import Layout from '../layout/index.vue'
export const constantRoutes = [{
  path: '/',
  component: Layout,
  redirect: '/application/list'
},
// activeMenu 的问题 需要加进去
{
  path: '/401',
  name: '401',
  hidden: true,
  component: () => import('@/views/error-page/401.vue'),
  meta: {
    title: '您暂无权限',
    icon: '',
    affix: true
  }
},
{
  path: '/error',
  name: 'error',
  hidden: true,
  component: () => import('@/views/error-page/error.vue'),
  meta: {
    title: '服务错误',
    icon: '',
    affix: true
  }
},
{
  path: "/screendeck",
  name: "ScreenDeck",
  hidden: true,
  meta: {
    title: "数据驾驶舱",
  },
  component: () => import("../views/bigscreen/index.vue"),
},
{
  path: "/screenboard",
  name: "ScreenBoard",
  hidden: true,
  meta: {
    title: "数据监控看板",
  },
  component: () => import("../views/screenboard/index.vue"),
},
{
  path: "/login",
  name: "Login",
  hidden: true,
  meta: {
    title: "登录",
    keepAlive: false
  },
  component: () => import("../views/Login/index.vue"),
},
];

// 路由调整



// 404页面
export const notFound = {
  path: '/:pathMatch(.*)*',
  name: 'not-found',
  component: NotFound,
  hidden: true
}

// 创建路由工厂方法
const createRouterFactory = () => {
  return createRouter({
    history: createWebHashHistory(),
    scrollBehavior: () => ({
      y: 0
    }),
    routes: constantRoutes
  })
}

const router = createRouterFactory()

// 批量新增路由
export function addRoutes (routes) {
  return new Promise((resolve) => {
    routes.forEach(item => {
      router.addRoute(item)
    })
    resolve()
  })
}

// 判断路由是否存在
const hasRoute = (route, list) => {
  let flag = false
  for (let i = 0; i < list.length; i++) {
    const item = list[i]
    if ((item.path === route.path) || (item.name === route.name)) {
      flag = true
      break
    } else if (item.children) {
      flag = hasRoute(route, item.children)
      if (flag) {
        break
      }
    } else {
      flag = false
    }
  }

  return flag
}

// 重置路由到最初的模样
export function resetRouter () {
  router.getRoutes().forEach((route) => {
    if (!hasRoute(route, constantRoutes)) {
      const {
        name
      } = route
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export default router;